package com.xie.demo.demo;

/**
 * @作者：xie
 * @时间：2023/8/17 19:25
 */
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Thread(new producer(synContainer)).start();
        new Thread(new consumer(synContainer)).start();
    }
}

class producer implements Runnable{
    SynContainer synContainer;
    public producer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }


    @Override
    public void run() {
        for(int i = 0; i < 20; i++){
            synContainer.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

class consumer implements Runnable{
    SynContainer synContainer;
    public consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            Chicken pop = synContainer.pop();
            System.out.println("消费了第"+pop.id+"只鸡");
        }
    }
}



//缓冲区
class SynContainer {
    Chicken[] chickens = new Chicken[10];
    int count;

    public synchronized void push(Chicken chicken){
        if(count == chickens.length){
            try {
                this.wait();
            }catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        chickens[count] = chicken;
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    public synchronized Chicken pop(){
        if(count == 0){
            try{
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        count --;
        this.notifyAll();
        return chickens[count];
    }

}

class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}


